from datetime import datetime
from django.conf import settings
from django.db.models import Q, F
from rest_framework import serializers

from apps.club_system.club.models import Club, ClubMember, ClubType
from apps.common.account.models import Account
from utils.data_dict import get_data_dict


class CLubListSerializer(serializers.ModelSerializer):
    apply_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    apply_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['type'] = instance.type.name  # 添加社团类型名称
        ret['member_count'] = instance.club_member.filter(is_active=True).count()  # 添加社团成员人数

        ret['business_unit'] = instance.business_unit.faculty_title if instance.business_unit else ''  # 添加指导单位名称
        # 返回主要成员
        role_dict = get_data_dict('club_role', default_value={})
        # todo: 这里可以优化
        main_members = ClubMember.objects.filter(~Q(role=1), is_active=True, club=instance) \
            .values('role', realname=F('account__realname'), wx_photo=F('account__wx_photo'),
                    politics_status=F('account__politics_status'))
        for member in main_members:
            member['role_name'] = role_dict.get(member['role'], 'None')
        ret['main_members'] = main_members
        account_qs = ClubMember.objects.filter(club=instance, is_active=True, role=3)\
            .values(realname=F('account__realname')).first()
        ret['account'] = account_qs['realname'] if account_qs else None
        # 添加头像
        ret['photo'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in instance.photo]
        now_time = datetime.now()
        ret['show_join'] = False    # 是否显示申请加入社团按钮
        if instance.apply_start_time and instance.apply_end_time:
            if instance.apply_start_time <= now_time <= instance.apply_end_time:
                ret['show_join'] = True
        return ret

    class Meta:
        model = Club
        fields = '__all__'


# 社团信息序列化器、不返回审核记录、普通学生及游客可以看的，列表和详情通用版本
class ClubBaseSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    apply_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    apply_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    type_id = serializers.IntegerField()
    type = serializers.CharField(read_only=True)
    business_unit_id = serializers.IntegerField()
    business_unit = serializers.SlugRelatedField(label='指导单位', slug_field='faculty_title', read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['type'] = instance.type.name  # 添加社团类型名称
        ret['member_count'] = instance.club_member.filter(is_active=True).count()  # 添加社团成员人数
        ret['account'] = instance.account.realname if instance.account else ''  # 添加创建人名字
        ret['business_unit'] = instance.business_unit.faculty_title if instance.business_unit else ''  # 添加指导单位名称
        # 返回主要成员
        role_dict = get_data_dict('club_role', default_value={})
        main_members = ClubMember.objects.filter(~Q(role=1), is_active=True, club=instance) \
            .values('role', realname=F('account__realname'), wx_photo=F('account__wx_photo'),
                    politics_status=F('account__politics_status'))
        for member in main_members:
            member['role_name'] = role_dict.get(member['role'], 'None')
        ret['main_members'] = main_members
        # 添加头像
        photo = instance.photo
        ret['photo'] = []
        ret['photo'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in photo]
        # 返回指导老师
        teacher_info = instance.club_member.select_related('account').get(club=instance, is_active=True, role=4).account
        ret['teacher_id'] = teacher_info.id
        ret['teacher_realname'] = teacher_info.realname
        return ret

    class Meta:
        model = Club
        exclude = ('file', 'image')


# 社团信息序列化器、返回审核记录、校团委、会长专用版本
class ClubPlusSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    apply_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    apply_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    first_check_status = serializers.CharField(read_only=True)
    second_check_status = serializers.CharField(read_only=True)
    type_id = serializers.IntegerField()
    type = serializers.CharField(read_only=True)
    business_unit_id = serializers.IntegerField()
    business_unit = serializers.SlugRelatedField(label='指导单位', slug_field='faculty_title', read_only=True)

    def to_representation(self, instance):  # 修 查询数据库太多了
        ret = super().to_representation(instance)
        ret['type'] = instance.type.name  # 添加社团类型名称
        ret['member_count'] = instance.club_member.filter(is_active=True).count()  # 添加社团成员人数
        # 添加会长姓名
        account_qs = ClubMember.objects.filter(club=instance, is_active=True, role=3) \
            .values(realname=F('account__realname')).first()
        ret['account'] = account_qs['realname'] if account_qs else None
        ret['telephone'] = instance.account.telephone  # 手机号码
        ret['business_unit'] = instance.business_unit.faculty_title if instance.business_unit else '' # 添加指导单位名称
        # 返回主要成员
        role_dict = get_data_dict('club_role', default_value={})
        main_members = ClubMember.objects.filter(~Q(role=1), is_active=True, club=instance) \
            .values('role', realname=F('account__realname'), wx_photo=F('account__wx_photo'),
                    politics_status=F('account__politics_status'))
        for member in main_members:
            member['role_name'] = role_dict.get(member['role'], 'None')
        ret['main_members'] = main_members
        # 添加头像
        ret['club_photo'] = [{ 'url': f"{settings.IMAGE_URL}{obj.get('data')}", 'name': obj.get('file_name')}
                             for obj in instance.photo]
        # 添加文件
        files_all = instance.file
        ret['club_files'] = []
        ret['club_files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in files_all]
        # 添加图片
        images_all = instance.image
        ret['club_images'] = []
        ret['club_images'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in images_all]
        # 添加审核历史
        ret['check_history'] = []
        check_qs = instance.club_check.order_by('-created_time').only(
            'account', 'check_opinion', 'check_status', 'check_level', 'created_time'
        )
        check_level_fomat = {1: '一级审核', 2: '二级审核'}
        for i in check_qs:
            tmp = {
                'account': i.account.realname,
                'check_opinion': i.check_opinion,
                'check_status': i.check_status,
                'check_level_name': check_level_fomat.get(i.check_level, '审核'),
                'created_time': i.created_time.strftime('%Y-%m-%d %H:%M')
            }
            ret['check_history'].append(tmp)

        # 返回指导老师
        try:
            teacher_info = instance.club_member.select_related('account').get(club=instance, is_active=True, role=4).account
            ret['teacher_id'] = teacher_info.id
            ret['teacher_realname'] = teacher_info.realname
            ret['teacher_username'] = teacher_info.username
            ret['teacher_faculty_title'] = teacher_info.faculty_title
        except ClubMember.DoesNotExist:
            ret['teacher_id'] = ''
            ret['teacher_realname'] = ''
            ret['teacher_username'] = ''
            ret['teacher_faculty_title'] = ''
        return ret

    class Meta:
        model = Club
        fields = '__all__'



class ClubSerializer(serializers.ModelSerializer):
    account = serializers.HiddenField(  # 默认为当前创建者
        default=serializers.CurrentUserDefault()
    )
    # 测试用
    # account_id = serializers.IntegerField()
    # account = serializers.StringRelatedField(read_only=True)
    apply_start_time = serializers.DateTimeField(allow_null=True, default=None)
    apply_end_time = serializers.DateTimeField(allow_null=True, default=None)
    type_id = serializers.IntegerField()
    type = serializers.CharField(read_only=True)
    business_unit_id = serializers.IntegerField()
    business_unit = serializers.SlugRelatedField(label='指导单位', slug_field='faculty_title', read_only=True)
    account_id = serializers.IntegerField(read_only=True)
    first_check_status = serializers.CharField(read_only=True)
    second_check_status = serializers.CharField(read_only=True)
    is_active = serializers.BooleanField(default=True, read_only=True)

    def update(self, instance, validated_data):
        # 更新时要将两个审核改为待审核
        validated_data['first_check_status'] = '待审核'
        validated_data['second_check_status'] = '待审核'
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    class Meta:
        model = Club
        fields = '__all__'

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # 添加头像
        photo = instance.photo
        ret['photo'] = []
        ret['photo'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in photo]
        # 添加文件
        files_all = instance.file
        ret['club_files'] = []
        ret['club_files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in files_all]
        # 添加图片
        images_all = instance.image
        ret['club_images'] = []
        ret['club_images'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in images_all]
        return ret


# 社团一级审核用的序列化类
class ClubFirstCheckSerialzier(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    apply_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    apply_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    def to_representation(self, instance):  # 修 查询数据库太多了
        ret = super(ClubFirstCheckSerialzier, self).to_representation(instance)
        ret['type'] = instance.type.name
        ret['business_unit'] = instance.business_unit.faculty_title if instance.business_unit else ''
        # 返回个人信息
        ret['realname'] = instance.account.realname
        ret['username'] = instance.account.username
        ret['student_community'] = instance.account.student_community
        ret['politics_status'] = instance.account.politics_status
        ret['faculty_title'] = instance.account.faculty_title
        # 添加头像
        photo = instance.photo
        ret['photo'] = []
        ret['photo'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in photo]
        # 添加文件
        files_all = instance.file
        ret['club_files'] = []
        ret['club_files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in files_all]
        # 添加图片
        images_all = instance.image
        ret['club_images'] = []
        ret['club_images'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in images_all]
        return ret

    class Meta:
        model = Club
        exclude = ('image', 'file',)


# 社团二级审核用的序列化类
class ClubSecondCheckSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    apply_start_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    apply_end_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)

    def to_representation(self, instance):  # 修 查询数据库太多了
        ret = super(ClubSecondCheckSerializer, self).to_representation(instance)
        ret['type'] = instance.type.name
        ret['business_unit'] = instance.business_unit.faculty_title if instance.business_unit else ''
        # ret['teacher'] = instance.club_member.get(role=4, is_active=True, club=instance).account.realname  # 添加指导老师
        # 返回个人信息
        ret['realname'] = instance.account.realname
        ret['username'] = instance.account.username
        ret['student_community'] = instance.account.student_community
        ret['politics_status'] = instance.account.politics_status
        ret['faculty_title'] = instance.account.faculty_title
        # 添加头像
        photo = instance.photo
        ret['photo'] = []
        ret['photo'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in photo]
        # 添加文件
        files_all = instance.file
        ret['club_files'] = []
        ret['club_files'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in files_all]
        # 添加图片
        images_all = instance.image
        ret['club_images'] = []
        ret['club_images'] = [{
            'url': f"{settings.IMAGE_URL}{obj.get('data')}",
            'name': obj.get('file_name'),
        } for obj in images_all]

        # 添加一级审核历史
        check_qs = instance.club_check.filter(check_level=1).order_by('-created_time').first()
        ret['first_check_opinion'] = check_qs.check_opinion if check_qs else ''

        return ret

    class Meta:
        model = Club
        exclude = ('image', 'file',)


# 成员序列化器
class ClubMemberSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)

    def to_representation(self, instance):  #
        ret = super().to_representation(instance)
        role_dict = get_data_dict('club_role', default_value={})
        ret['role'] = role_dict.get(instance.role, 'None')
        # 返回个人信息
        ret['realname'] = instance.account.realname
        ret['username'] = instance.account.username
        ret['student_community'] = instance.account.student_community
        ret['politics_status'] = instance.account.politics_status
        ret['faculty_title'] = instance.account.faculty_title
        return ret

    class Meta:
        model = ClubMember
        fields = ('account', 'created_time', 'updated_time', 'is_active')


class ClubNameListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Club
        fields = ('id', 'name')
